<?php
namespace App\Console\Commands;

use App\Http\Model\Hint;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Carbon\Carbon;
use PDO;

class CommandChangeWechatPay extends Command
{
    protected $nowWechatBussinessKey = 'PAY:WECHAT:NOW:USE';//目前微信使用中的商户配置 string PAY:WECHAT:NOW:USE {strign}
    protected $wechatBussinessTimes = 'PAY:WECHAT:NOW:COUNTS:';//目前微信使用中的商户配置循环次数 string PAY:WECHAT:NOW:COUNTS:{int}=>{int}
    protected $config;
    protected $sysConfigTable = 'system_config';//系统全局配置
    protected $rechargeOrderTable = 'finance_recharge_order';//充值订单

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'CommandChangeWechatPay';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '轮换微信商户配置';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->config = config('pay');
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        do{
            //目前使用中的配置
            $nowUseRedis = Redis::get($this->nowWechatBussinessKey);
            $nowUse = empty($nowUseRedis) ? 'pay_wx_app_3' : $nowUseRedis;
            Redis::set($this->nowWechatBussinessKey, $nowUse);
            //获取系统配置中的配置商户号
            $sysConfig = DB::table($this->sysConfigTable)->where('key','sys_wechat_pay_mch_ids')->first();
            $sysConfig = objToArray($sysConfig);
            if(empty($sysConfig)){
                break;
            }
            $sysValue = json_decode($sysConfig['value'],true);
            $machList = array_column($sysValue['list'],null,'value');
            $mch_arr = array_column($sysValue['list'],'value');

            //系统配置阀值
            $outLimit = $sysValue['max_value'];
            $payConfig = $this->config[$nowUse];
            if(empty($payConfig)){
                break;
            }
            $mchId = $payConfig['mch_id'];
        
            if(!in_array($mchId,$mch_arr)){
                break;
            }
            //时间
            $today = Carbon::today()->startOfDay();
            $endDay = Carbon::today()->endOfDay();
            $diffTime = Carbon::now()->diffInSeconds($endDay);
            //轮次
            $mchIdRoundValue = Redis::get($this->wechatBussinessTimes.$mchId);
            if(!empty($mchIdRoundValue)){
                $outLimit = $sysValue['max_value'] + $mchIdRoundValue;
            }
            //查询目前充值金额
            $sum = DB::table($this->rechargeOrderTable)
                    ->where('mch_id',$mchId)
                    ->where('status',1)
                    ->whereBetween('create_time',[$today,$endDay])
                    ->sum('price');
            if(($sum/100) >= $outLimit){
                //切换商户
                $next = $this->get_next($mch_arr, $mchId);
                $mch_id = $mch_arr[$next];
                Redis::set($this->nowWechatBussinessKey,$machList[$mch_id]['key']);
                Redis::INCRBY($this->wechatBussinessTimes.$mchId,$outLimit);
                Redis::EXPIRE($this->wechatBussinessTimes.$mchId, $diffTime);
            }
        }while(false);
        return true;
    }

    //获取下一个元素
    public function get_next($array, $search){
        $key = array_search($search,$array);
        $next = $key + 1;
        $allKeys = array_keys($array);
        if(!in_array($next,$allKeys)){
            $next = 0;
        }
        return $next;
    }
}